/**
 * 指标映射管理
 *
 * Created by shijian
 * Date 2018/10/17
 */
var scripts = [null,
    ctx + '/resource/plugins/ace/components/jqGrid/js/jquery.jqGrid.js',
    ctx + '/resource/plugins/ace/components/jqGrid/js/i18n/grid.locale-cn.js',
    ctx + '/resource/plugins/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js',
    ctx + '/resource/plugins/ace/components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.zh-CN.min.js',
    ctx + '/resource/plugins/bootstrapvalidator/js/bootstrapValidator.min.js',
    ctx + '/resource/plugins/bootstrapvalidator/js/language/zh_CN.js',
    ctx + '/resource/plugins/jquery.jqGrid.patch.src.js',
    null];
pageContentArea.ace_ajax('loadScripts', scripts, function () {
    jQuery(function ($) {
        var grid_selector = '#grid-table';
        var $grid_selector = $(grid_selector);
        var pager_selector = '#grid-pager';
        var parent_column = $grid_selector.closest('[class*="col-"]');
        var colNames = [
            '主键ID',
            '指标编码',
            '源指标编码',
            '源指标系统编码',
            '指标描述',
            '删除标记',
            '创建人',
            '创建时间',
            '修改人',
            '修改时间'
        ];
        var width = pageContentArea.width() / colNames.length;
        var colModels = [
            {name: 'relationId', index: 'relationId', width: width, hidden: true},
            {name: 'kpiCode', index: 'kpiCode', width: width},
            {name: 'srcKpiCode', index: 'srcKpiCode', width: width},
            {name: 'systemCode', index: 'systemCode', width: width},
            {name: 'comments', index: 'comments', width: width},
            {name: 'isDelete', index: 'isDelete', width: width, hidden: true},
            {name: 'creater', index: 'creater', width: width, hidden: true},
            {name: 'createDate', index: 'createDate', width: width, hidden: true},
            {name: 'modifier', index: 'modifier', width: width, hidden: true},
            {name: 'modifieDate', index: 'modifieDate', width: width, hidden: true}
        ];
        $grid_selector.jqGrid({
            url: ctx + '/tbCdeKpiRelationSrc/queryPageList',
            mtype: 'post',
            datatype: 'json',
            height: '100%',
            colNames: colNames,
            colModel: colModels,
            autowidth: true,
            altRows: true,
            rownumbers: true,
            viewrecords: true,
            multiselect: true,
            multiboxonly: true,
            rowNum: rowNum,
            rowList: rowList,
            pager: pager_selector,
            sortname: 'relationId',
            sortorder: 'asc',
            jsonReader: jsonReader,
            beforeRequest: function () {
                var postData = {};
                $('#queryPanel').find('[name^="search."]').each(function () {
                    var $this = $(this);
                    postData[$this.attr('name').replace(/search\./, '')] = $this.val();
                });
                $.extend($grid_selector.getGridParam('postData'), postData);
            },
            loadComplete: function () {
                setTimeout(function () {
                    $grid_selector.jqGrid('setGridWidth', parent_column.width());
                }, 20);
            },
            ondblClickRow: viewGridRow
        });

        //navButtons
        $grid_selector.jqGrid('navGrid', pager_selector, {
            add: false, edit: false, del: false, search: false, view: false, refresh: true,
            refreshicon: 'ace-icon fa fa-refresh green'
        }).navSeparatorAdd(pager_selector, {
            sepclass: 'ui-separator',
            sepcontent: ''
        }).navButtonAdd(pager_selector, {
            caption: '',
            title: '查看详细信息',
            buttonicon: 'ace-icon fa fa-search-plus info',
            onClickButton: viewGridRow,
            position: 'first'
        }).navButtonAdd(pager_selector, {
            caption: '',
            title: '导出Excel',
            buttonicon: 'ace-icon fa fa-file-excel-o green',
            onClickButton: expRowsToExcel,
            position: 'last'
        });

        // Form表单
        var theForm = $('#editTbCdeKpiRelationSrcForm');

        $('#addBtn').click(function () {
            // 重置表单验证
            resetValidator();
            // 隐藏隐藏项
            $('.show').removeClass('show').addClass('hidden');
            // 显示保存按钮
            $('#saveTbCdeKpiRelationSrcBtn').removeClass('hidden');
            // 重置表单基本元素
            theForm.formReset();
            // 启用deptCode验证
            $(':input[name="srcKpiCode"]').removeAttr('readonly', 'readonly');
            theForm.bootstrapValidator('enableFieldValidators', 'srcKpiCode', true);
            // 显示弹出层
            $.launchDialog('tbCdeKpiRelationSrcModal');
        });

        $('#editBtn').click(function () {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要编辑的记录!');
            } else if (rowIds.length > 1) {
                $(this).dynamicPop('不能选择多条记录编辑, 请选择一条记录!');
            } else {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                var relationId = $grid_selector.jqGrid('getRowData', rowId).relationId;
                // 重置表单验证
                resetValidator();
                $.ajax({
                    type: 'post',
                    async: true,// 异步请求
                    url: ctx + '/tbCdeKpiRelationSrc/querySingle',
                    dataType: 'json',
                    data: {
                        relationId: relationId
                    },
                    beforeSend: function () {
                        // 重置表单
                        theForm.formReset();
                        // 隐藏隐藏项
                        $('.show').removeClass('show').addClass('hidden');
                        // 禁用deptCode验证
                        $(':input[name="srcKpiCode"]').attr('readonly', 'readonly');
                        theForm.bootstrapValidator('enableFieldValidators', 'srcKpiCode', false);
                        // 显示保存按钮
                        $('#saveTbCdeKpiRelationSrcBtn').removeClass('hidden');
                    },
                    success: function (data) {
                        // Form表单赋值
                        theForm.setForm(data);
                        // 显示Form表单
                        $.launchDialog('tbCdeKpiRelationSrcModal');
                    }
                });
            }
        });

        $('#delBtn').click(function () {
            // 获取选中的列表项
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds.length > 0) {
                $(this).confirm('确认要删除吗？', function () {
                    var ids = new Array();
                    $.each(rowIds, function (idx, rowId) {
                        var row = $grid_selector.jqGrid('getRowData', rowId);
                        ids.push(row.relationId);
                    });
                    $.ajax({
                        async: true,// 异步请求
                        type: 'post',
                        url: ctx + '/tbCdeKpiRelationSrc/delete',
                        dataType: 'json',
                        data: {
                            ids: ids.join(',')
                        },
                        success: function (data) {
                            if (data) {
                                // 删除成功将表格刷新
                                $grid_selector.trigger('reloadGrid', [{page: 1}]);
                            }
                        }
                    });
                });
            } else {
                $(this).dynamicPop('请从列表中选择一条记录删除!');
            }
        });

        // 查看
        function viewGridRow() {
            var rowIds = $grid_selector.jqGrid('getGridParam', 'selarrrow');
            if (rowIds == null || rowIds.length == 0) {
                $(this).dynamicPop('请选择要查看的记录!');
            } else if (rowIds.length > 1) {
                $(this).dynamicPop('不能选择多条记录查看, 请选择一条记录!');
            } else {
                var rowId = $grid_selector.jqGrid('getGridParam', 'selrow');
                var relationId = $grid_selector.jqGrid('getRowData', rowId).relationId;
                // 重置表单验证
                resetValidator();
                $.ajax({
                    type: 'post',
                    async: true,// 异步请求
                    url: ctx + '/tbCdeKpiRelationSrc/querySingle',
                    dataType: 'json',
                    data: {
                        relationId: relationId
                    },
                    beforeSend: function () {
                        // 重置表单
                        theForm.formReset();
                        // 显示隐藏项
                        $('.hidden').removeClass('hidden').addClass('show');
                        // 隐藏保存按钮
                        $('#saveTbCdeKpiRelationSrcBtn').addClass('hidden');
                        $(':input[name="srcKpiCode"]').removeAttr('readonly');
                    },
                    success: function (data) {
                        // Form表单赋值
                        theForm.setForm(data);
                        // 显示Form表单
                        $.launchDialog('tbCdeKpiRelationSrcModal');
                    }
                });
            }
        }

        // 导出excel
        function expRowsToExcel() {
            var colFieldViewNames = new Array();
            var colFieldNames = new Array();
            $.each(colModels, function (idx, obj) {
                if (obj.hidden == false || obj.hidden == undefined) {
                    colFieldNames.push(obj.index);
                    colFieldViewNames.push(colNames[idx]);
                }
            });
            var sortName = $grid_selector.jqGrid('getGridParam', 'sortname');// 排序列
            var sortOrder = $grid_selector.jqGrid('getGridParam', 'sortorder');// 排序方式：desc、asc
            var postData = {};
            $('#queryPanel').find('[name^="search."]').each(function () {
                var $this = $(this);
                postData[$this.attr('name').replace(/search\./, '')] = $this.val();
            });
            postData.titles = colFieldViewNames;
            postData.fields = colFieldNames;
            postData.sidx = sortName;
            postData.sord = sortOrder;
            $.ajax({
                type: 'post',
                async: true,// 异步请求
                url: ctx + '/tbCdeKpiRelationSrc/expExcel',
                dataType: 'json',
                data: postData,
                success: function (data) {
                    downloadFile(data.result);// 下载文件
                }
            });
        }

        // 表单验证
        function formValidator() {
            theForm.bootstrapValidator({
                group: '.rowGroup',
                message: 'This value is not valid',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    kpiCode: {
                        message: '指标编码验证失败',
                        validators: {
                            notEmpty: {
                                message: '指标编码不能为空'
                            },
                            stringLength: {
                                max: 36,
                                message: '指标编码长度不能大于36'
                            }
                        }
                    },
                    srcKpiCode: {
                        message: '源指标编码验证失败',
                        validators: {
                            threshold: 1, //有1字符以上才发送ajax请求
                            remote: {//ajax验证,result:{"valid",true or false}, 表示正确: {"valid",true}
                                url: ctx + '/tbCdeKpiRelationSrc/checkInputField',
                                message: '源指标编码已存在',
                                delay: 1000,//设置1秒发送一次ajax（默认输入一个字符，提交一次）
                                type: 'POST',//请求方式
                                //自定义提交数据, 默认值提交当前input value
                                data: function (validator) {
                                    return {
                                        inputName: 'srcKpiCode',
                                        inputValue: $('[name="srcKpiCode"]').val()
                                    };
                                }
                            },
                            notEmpty: {
                                message: '源指标编码不能为空'
                            },
                            stringLength: {
                                max: 36,
                                message: '源指标编码长度不能大于36'
                            }
                        }
                    },
                    systemCode: {
                        message: '源指标系统编码验证失败',
                        validators: {
                            notEmpty: {
                                message: '源指标系统编码不能为空'
                            },
                            stringLength: {
                                max: 36,
                                message: '源指标系统编码长度不能大于36'
                            }
                        }
                    },
                    comments: {
                        message: '指标描述验证失败',
                        validators: {
                            stringLength: {
                                max: 250,
                                message: '指标描述长度不能大于250'
                            }
                        }
                    }
                }
            });
        }

        // 初始化表单验证
        formValidator();

        // 保存
        $('#saveTbCdeKpiRelationSrcBtn').click(function () {
            //开启验证
            theForm.data('bootstrapValidator').validate();
            if (theForm.data('bootstrapValidator').isValid()) {
                $.ajax({
                    async: true,// 异步请求
                    type: 'post',
                    dataType: 'json',
                    url: ctx + '/tbCdeKpiRelationSrc/save',
                    data: JSON.stringify(theForm.serializeObject()),
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success == true) {
                            $grid_selector.trigger('reloadGrid', [{page: 1}]);
                            // 关闭窗口
                            $('#tbCdeKpiRelationSrcModal').modal('hide');
                            $.successMessage(data.msg, pageContentArea);
                        } else {
                            $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', theForm);
                        }
                    },
                    error: function () {
                        $.alertMessage('抱歉! 系统异常, 请联系管理员处理, 或稍后再试. ', theForm);
                    }
                });
            }
        });

        //重置表单验证
        function resetValidator() {
            var bootstrapValidator = theForm.data('bootstrapValidator');
            if (bootstrapValidator) {
                bootstrapValidator.destroy();
                theForm.data('bootstrapValidator', null);
                formValidator();
            }
        }

        // 显示隐藏查询条件
        $('#searBtn').click(function () {
            $(this).find('i').toggleClass('fa-arrow-down');
            $(this).find('i').toggleClass('fa-arrow-up');
        });

        $('#searchBtn').click(function () {
            $grid_selector.trigger('reloadGrid', [{page: 1}]);
        });

        // 重置查询表单
        $('#resetBtn').click(function () {
            $('#queryPanel').find(':input(:text)').each(function () {
                $(this).val('');
            });
            $('#queryPanel').find('input[type=checkbox],input[type=radio]').each(function () {
                $(this).removeAttr('checked');
            });
            reloadJqGrid('json');
        });

        // 刷新JqGrid列表
        function reloadJqGrid(datatype) {
            $grid_selector.jqGrid('setGridParam', {datatype: datatype}).trigger('reloadGrid', [{page: 1}]);
        }

        // 初始化日期控件
        $('.date-picker').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            todayHighlight: true,
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        }).next().on(ace.click_event, function () {
            $(this).prev().focus();
        });

        $('.input-daterange').datepicker({
            language: 'zh-CN',
            autoclose: true,//选中之后自动隐藏日期选择框
            //todayHighlight: true,
            clearBtn: true,//清除按钮
            format: 'yyyy-mm-dd'//日期格式
        });

        //resize to fit page size
        $(window).on('resize.jqGrid', function () {
            $grid_selector.jqGrid('setGridWidth', parent_column.width());
        });

        $(document).one('ajaxloadstart.page', function (e) {
            $.jgrid.gridDestroy(grid_selector);
            $('.ui-jqdialog').remove();
        });

        // 通过该方法来为每次弹出的模态框设置最新的zIndex值，从而使最新的modal显示在最前面
        $(document).on('show.bs.modal', '.modal', function () {
            var zIndex = 1040 + (10 * $('.modal:visible').length);
            $(this).css('z-index', zIndex);
            setTimeout(function () {
                $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
            }, 0);
        });

    });

});
